package com.budwk.app.sqfwV2.generator.dayingRoadExcel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.dto.dto.ExtraProblemVo;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.image.FireSafetyOnDayingRoadExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.DayingRoadFileServiceEnum;
import com.budwk.app.sqfwV2.enums.RectificateTimeEnum;
import com.budwk.app.sqfwV2.enums.dayingRoad.KeySafetyIndustriesEnum;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 云岩区消防安全重大风险隐患台账
 */

@IocBean
@Slf4j
public class KeyLocationBookGenerator extends BaseTemplateExcelGenerator implements DayingRoadExcelGenerator {

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    @Override
    protected String getTemplateName() {
        return DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FIRE_SAFETY.getFilePath();
    }

    /**
    * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
    *
    * @return 文件名名称
    */
    @Override
    public String getDownloadFileName() {
        //TODO 在这里返回你生成的文件名名称，注意注意注意不用带上后缀
        return DayingRoadPdfComponent.getDictName(DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_FIRE_SAFETY.getCode(), null);
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        excelParam.put("downloadDateStr", DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        excelParam.put("district", DayingRoadPdfComponent.getDistrict(excelCreateParam.getBaseExcelParamDTO().getDistrict()));
    }

    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        // 1 获取数据对象
        List<Sqfw_formSummary_new> summaryList = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        log.info("KeyLocationBookGenerator customerPopularSheetDataParam param: {}", JSONObject.toJSONString(summaryList));
        // 2 构建参数map
        int num = 1;
        SysDictService dictService = NutzIocUtils.getBean(SysDictService.class);
        // 获取主管部门
        List<SysDictVO> departDicts = dictService.listDictByCode(DictConstants.COMPETENT_DEPART_TYPES);
        for (Sqfw_formSummary_new summary : summaryList) {
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
            log.info("KeyLocationBookGenerator customerPopularSheetDataParam roadPdfDTO: {}", JSONObject.toJSONString(roadPdfDTO));
            // 1 是否满足生成条件
            if (!isGenerateExcel(roadPdfDTO)) {
                continue;
            }
            // 2 构建参数map
            Map<String, Object> map = buildExcelMap(roadPdfDTO, departDicts);
            map.put("district", StrUtil.replaceNullStr(summary.getDistrict()));
            map.put("num", num ++);
            listMap.add(map);
        }
    }

    private Map<String, Object> buildExcelMap(FireSafetyOnDayingRoadPdfDTO roadPdfDTO, List<SysDictVO> departDicts) {
        Map<String, Object> map = new HashMap<>();
        // 1 基本参数
        map.put("placeName", StrUtil.replaceNullStr(roadPdfDTO.getPlaceName()));
        map.put("competentDepartmentName", CommonConstants.HORIAONTAL_LINE);
        if (StringUtils.isNotEmpty(roadPdfDTO.getCompetentDepartment())) {
            Optional<SysDictVO> optional = departDicts.stream().filter(d -> roadPdfDTO.getCompetentDepartment().equals(d.getCode())).findFirst();
            map.put("competentDepartmentName", optional.isPresent() ? optional.get().getName() : roadPdfDTO.getCompetentDepartment());
        }
        map.put("operator", StrUtil.replaceNullStr(roadPdfDTO.getOperator()));
        map.put("operatorTelephone", StrUtil.replaceNullStr(roadPdfDTO.getOperatorTelephone()));
        map.put("rectifyingDangersMeasures", StrUtil.replaceNullStr(roadPdfDTO.getRectifyingDangersMeasures()));
        // 检查31个问题是否整改完毕
        List<String> noNames = new ArrayList<>();
        String recStatus = "已整改"; // 是否全部是期限整改
        for (SafeCheckTaskParamDataDTO other : roadPdfDTO.getKeySafetyIndustries()) {
            KeySafetyIndustriesEnum e = KeySafetyIndustriesEnum.getEnumByCode(other.getFields());
            // 和默认值不一致 则是存在问题的
            if (!other.getKey().equals(e.getDefaultValue())) {
                noNames.add(e.getDesc());
            }
            // 判断是否为限期整改
            if (RectificateTimeEnum.isDeadlineRectification(other, e.getDefaultValue())) {
                recStatus = "整改中";
            }
        }
        map.put("safetyRisk", noNames.size() > 0 ? String.join("、", noNames) : "无");
        map.put("recStatus",noNames.size() > 0 ? recStatus : "");
        return map;
    }
    /**
     * ●当【a5】状态为【大型商场、超市、酒店】、
     * 【幼儿园、寄宿制学校、社会福利机构】、
     * 【医院、诊所、卫生服务站】、
     * 【劳动密集型企业、多业态混合经营场所】、
     * 【其他重点消防安全场所】五项中任意一项时，生成此表单。
     * @param roadPdfDTO
     * @return
     */
    public boolean isGenerateExcel(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 判断a5是否为重点场所 选择重点场所 生成表格
        return DayingRoadPdfComponent.isKeyLocations(roadPdfDTO);
    }

    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    /**
     * 如果在遍历之前就能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelCreateParam excel生成所需的最为全面的数据
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return DayingRoadPdfComponent.getSqfwExcelJudgeRes(excelCreateParam, new KeyLocationBookGenerator());
    }

    /**
    * 如果在遍历之后能够判断excel是否生成，那么就在这个方法中进行判断
    * @param excelParam excel已经填充的部分数据
    */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return FireSafetyOnDayingRoadExcelImageConfigBO.class;
    }
}
